<?php

/**
 * this class handles the actions for a simple modular content controller
 *
 */
class FRM_Controller_Action_Admin_Abstract extends FRM_Controller_Action_Abstract
{
	/**
	 * Темплей по умолчанию
	 *
	 * @var string
	 */
	protected $defaultTemplate = 'index.tpl';

	/**
     * Текущее значение ключевого поля
     *
     * @var int
     */
	protected $_recordId;

	/**
     * Тепущая запись
     *
     * @var zend_db_table_row
     */
	protected $_currentId;

	protected $windowFormWidth = 500;

	protected $langs = array();

	protected $localizedFields = array();

	protected $fields = array();

	/**
	 * Enter description here...
	 *
	 * @var FRM_View_Ext
	 */

	protected $validationRules = array();
	protected $validationErrors = array();


	/**
     * Инициализация
     * 
	 */
	public function init()
	{
		$this->view->currentAccess = FRM_ACL::getAccess();

		//Вызыавем тригер
		$this->beforeInit();

		//Вызыавем тригер
		$this->afterInit();

		//Запускаем иниализаци родителя
		parent::init();
		if(!is_null($this->_model)){



			$this->fields = $this->_model->getFields() ;

			if(method_exists($this->_model, 'getLocalizedFields')){
				$this->localizedFields = $this->_model->getLocalizedFields();
			}

			if(is_null($this->localizedFields)){
				$this->localizedFields = array();
			}

			if(method_exists($this->_model, 'getLangs')){
				$this->langs = $this->_model->getLangs();
			}

			if(is_null($this->langs)){
				$this->langs = array();
			}

		}
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
	}

	public function indexAction()
	{

	}

	public function validate2Action(){
		$this->_helper->viewRenderer->setNoRender();
		$errors= array();
		foreach ($this->validationRules as $k=>$v){
			$field = $k;
			$value = isset($_POST[$k])?trim($_POST[$k]):'';
			$id = isset($_POST['id'])?intval($_POST['id']):0;

			if($value){

				$v = new FRM_Tools_Validation($this->_model, $this->validationRules);

				$res =  $v->validateField($field, $value, $id);

				if(!$res['valid']){
					if(!empty($this->validationErrors[$k])){
						$errors[] = $this->validationErrors[$k];
					}else {
						$errors[] = $res['reason'];
					}
				}
			}else {
				if(!empty($this->validationErrors[$k])){
					$errors[] = $this->validationErrors[$k];
				}else {
					$errors[] = 'Ошибка';

				}
			}


		}
		
		$error = (count($errors))?implode("<br /> \n", $errors):0;
		
		$this->getResponse()->setBody($error);

	}

	/**
	 * Enter description here...
	 *
	 */
	public function gridAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		if(!is_null($this->_model)){
			$ext = new FRM_View_Ext($this->_model, TEMP_JS,  $this->_request->getModuleName(), $this->_request->getControllerName(), $this->_request->getActionName(), $this->windowFormWidth);
			$this->getResponse()->setBody($ext->renderWindow('grid'));
		}
	}

	public function extgridAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		if(!is_null($this->_model)){
			$ext = new FRM_View_Ext($this->_model, TEMP_JS,  $this->_request->getModuleName(), $this->_request->getControllerName(), $this->_request->getActionName(), $this->windowFormWidth);
			$this->getResponse()->setBody($ext->renderWindow('expandGrid'));
		}
	}

	public function customgridAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		if(!is_null($this->_model)){
			$ext = new FRM_View_Ext($this->_model, TEMP_JS,  $this->_request->getModuleName(), $this->_request->getControllerName(), $this->_request->getActionName(), $this->windowFormWidth);
			$this->getResponse()->setBody($ext->renderWindow('customGrid'));
		}
	}


	/**
	 * Enter description here...
	 *
	 */

	public function treedataAction(){
		$this->_helper->viewRenderer->setNoRender();
		$v = isset($_POST[$this->_model->getTreeFieldName()])?intval($_POST[$this->_model->getTreeFieldName()]):0;
		//print $v;
		$this->getResponse()->appendBody(Zend_Json_Encoder::encode($this->_model->getTreeData($v)));
	}

	public function treeAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		if(!is_null($this->_model)){
			$ext = new FRM_View_Ext($this->_model, TEMP_JS,  $this->_request->getModuleName(), $this->_request->getControllerName(), $this->_request->getActionName(), $this->windowFormWidth);
			$this->getResponse()->setBody($ext->renderWindow('tree'));
		}
	}

	public function galerydataAction(){

		$this->_helper->viewRenderer->setNoRender();
		$galery = new Admin_Offers_Galleries();
		$galery->setOffer($this->_request->getParam('id', 0));
		$this->getResponse()->setBody(Zend_Json_Encoder::encode(array("images"=>$galery->getImages())));
	}

	/**
	 * Получить список записей в джсон формате для extjs
	 *
	 */
	public function listAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		/**
		 * Получаем параметры
		 */
		$dir = (isset($_POST['dir']) && strtoupper($_POST['dir'])==='DESC')?'DESC':'ASC';
		//print $dir;
		$limit = (isset($_POST['limit']) && intval($_POST['limit']))?intval($_POST['limit']):25;
		$start = (isset($_POST['start']) && intval($_POST['start']))?intval($_POST['start']):0;
		$sort = (isset($_POST['sort']))?$_POST['sort']:'id';

		$p = $this->_model->getTreeFieldName();

		$parent = (isset($_POST[$p]))?intval($_POST[$p]):null;

		$lang = (isset($_POST['lang']))?$_POST['lang']:null;

		$this->setLang($lang);

		$where = null;

		if(!is_null($parent)){
			$where	="$p = $parent";
		}


		//Выбераем даные
		$data = array("totalCount"=>(string)$this->_model->getRowCounts($where), 'data'=>$this->_model->getList($where, "$sort $dir", $limit,$start));

		//Возращаем
		$this->getResponse()->appendBody(Zend_Json_Encoder::encode($data));
	}

	/**
	 *  Сохраняем / Добавляем
	 * 
	 */
	public function saveAction()
	{
		$this->_helper->viewRenderer->setNoRender();

		//Вызыавем тригер
		$this->before();

		//Вызываем добавлений в модели
		$this->_currentId = $this->_model->saveData();

		//Вызыавем тригер
		$this->after();
	}

	public function comboAction(){
		$this->_helper->viewRenderer->setNoRender();

		$id = isset($_POST['id'])?intval($_POST['id']):null;

		$this->getResponse()->setBody(Zend_Json_Encoder::encode($this->_model->getCombo($id)));
	}

	public function uploadAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		FRM_Tools_Upload::UploadAdmin($this->_model->getFields());
		$this->getResponse()->appendBody("{ success: true}");
		//print_r($_SESSION);
	}

	/**
	 * Орабатываем экшен редактирование
	 * 
	 */
	public function editAction()
	{
		if(!is_null($this->_model)){
			$this->_helper->viewRenderer->setNoRender();
			$this->_recordId = $_POST['id'];
			//Вызыавем тригер
			$this->afterOpen();
			//Возращаем данные
			$a = $this->_model->getRowById($this->_recordId);

			if(count($this->localizedFields)){
				$table = new FRM_Db_Table_Localizaton($this->_model->getTableName());
				foreach ($this->langs as $key => $lang){
					$res = $table->find($this->_recordId, $key)->current();
					if(!is_null($res)){
						$res = $res->toArray();
					}
					foreach($this->localizedFields as $v){
						$a[$v][$key] = (!is_null($res) && !empty($res))?$res[$v]:'';
					}
				}

			}

			if(!count($a)){
				$data = array("success"=>false);
			}else {
				$data = array("success"=>true, 'data'=>array($a));
			}

			$this->getResponse()->appendBody(Zend_Json_Encoder::encode($data));
			//Вызыавем тригер
			$this->afterOpen();
		}
	}

	/**
	 * Орабатываем экшен удаление
	 * 
	 */
	public function deleteAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		//Получаем id
		$recordsId = Zend_Json_Decoder::decode($_POST['delete']);

		foreach ($recordsId[0] as $recordId)
		{
			$this->_recordId = $recordId;

			//Если id больше нуля - вызываем удаление
			if($this->_recordId > 0)
			{
				//Вызыавем тригер
				$this->beforeDelete();
				//Вызываем удаление
				$this->_model->deleteData($this->_recordId);
				//Вызыавем тригер
				$this->afterDelete();
			}
		}
		$this->getResponse()->appendBody('[{"success":true}]');

	}

	/**
	 * Орабатываем экшен показать запись
	 * 
	 */

	public function showAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		//Получаем id
		$this->_recordId = $this->_request->getParam('id', 0);

		//Если id больше нуля - вызываем показать
		if($this->_recordId > 0)
		{
			//Вызыавем тригер
			$this->beforeShow();
			//Вызываем показать
			$this->_model->show($this->_recordId);
			//Вызываем тригер
			$this->afterShow();
		}
		$this->getResponse()->appendBody('[{"success":true}]');
	}

	public function validateAction(){
		$this->_helper->viewRenderer->setNoRender();
		$this->getResponse()->setBody(Zend_Json_Encoder::encode($this->_model->validate($_POST)));
	}

	/**
	 * Орабатываем экшен спрятать запись
	 * 
	 */
	public function hideAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		//Получаем id
		$this->_recordId = $this->_request->getParam('id', 0);

		//Если id больше нуля - вызываем спрятать
		if($this->_recordId > 0)
		{
			//Вызыавем тригер
			$this->beforeHide();
			//Вызывааем стратать
			$this->_model->hide($this->_recordId);
			//Вызыавем тригер
			$this->afterHide();
		}
		$this->getResponse()->appendBody('[{"success":true}]');
	}

	/**
	 * Орабатываем экшен перемесить више запись
	 * 
	 */
	public function upAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		//Получаем id
		$this->_recordId = $this->_request->getParam('id', 0);

		//Если id больше нуля - вызываем перемесить
		if($this->_recordId > 0)
		{
			//Вызыавем тригер
			$this->beforeUp();
			//Вызыавем перемесить
			$this->_model->up($this->_recordId);
			//Вызыавем тригер
			$this->afterUp();
		}
		$this->getResponse()->appendBody('[{"success":true}]');
	}

	/**
	 * Орабатываем экшен перемесить ниже запись
	 * 
	 */
	public function downAction()
	{
		$this->_helper->viewRenderer->setNoRender();
		//Получаем id
		$this->_recordId = $this->_request->getParam('id', 0);

		//Если id больше нуля - вызываем перемесить
		if($this->_recordId > 0)
		{
			//Вызыавем тригер
			$this->beforeDown();
			//Вызыавем перемесить
			$this->_model->down($this->_recordId);
			//Вызыавем тригер
			$this->afterDown();
		}
		$this->getResponse()->appendBody('[{"success":true}]');

	}

	public function setLang($lang){
		if(!is_null($lang) && !is_null($this->_model) && count($this->localizedFields)){
			if(method_exists($this->_model, 'getActualLang')){
				$actualLang = $this->_model->getActualLang();
				if($actualLang !== $lang){
					$this->_model->setCurrentSelect(null);
					$this->_model->setActualLang($lang);
					$this->_model->init();
				}
			}
		}
		return $this;
	}


	//Тригера

	public function before(){}

	public function after(){
		if ($this->_currentId){
			//print_r($this->_model->getRelations());
			foreach ($this->_model->getRelations() as $k=>$v){
				if(isset($v['className']) && class_exists($v['className'])){
					if(isset($v['parram'])){
						$model = new $v['className']($v['parram']);
					}else{
						$model = new $v['className']();
					}
					//$model = new FRM_Db_Table_Localizaton();

					$model->setPostPart($k);

					$rel = $this->_model->getRelations();
					$rel[$k]['extra'] = array('id'=>$this->_currentId);
					$model->setRelations($rel);
					$model->saveData();
				}
			}

			$data = array("success"=>true, 'id'=>$this->_currentId);
		}
		else{
			$data = array("success"=>false, 'msg'=>"Не пройшло");
		}
		$this->getResponse()->appendBody(Zend_Json_Encoder::encode($data));
	}

	public function afterEdit(){



		if ($this->_currentId)
		$data = array("success"=>true, 'id'=>$this->_currentId);
		else
		$data = array("success"=>false, 'msg'=>"Не пройшло");
		$this->getResponse()->appendBody(Zend_Json_Encoder::encode($data));
	}

	public function beforeInit(){}
	public function afterInit(){}
	public function beforeOpen(){}
	public function afterOpen(){}
	public function beforeDelete(){}
	public function afterDelete(){}
	public function beforeShow(){}
	public function afterShow(){}
	public function beforeHide(){}
	public function afterHide(){}
	public function beforeUp(){}
	public function afterUp(){}
	public function beforeDown(){}
	public function afterDown(){}
}